import React from 'react';
import {ListView, PullToRefresh, Button, Card, List, WhiteSpace, WingBlank, Carousel, Modal} from "antd-mobile";
import './MovieInfo.scss'
import {Link} from "react-router-dom";
import http from "../../../util/http";
import {DoubleLeftOutlined} from "@ant-design/icons";
import ReviewList from "../../../components/ReviewList";
import cookies from 'react-cookies'

const Item = List.Item;
const Brief = Item.Brief;

const NUM_ROWS = 1;
let pageIndex = 0;

//初始化数据量数组，增加数据量数组
function genData(pIndex = 0) {
    const dataArr = [];
    for (let i = 0; i < NUM_ROWS; i++) {
        dataArr.push(`row - ${(pIndex * NUM_ROWS) + i}`);
    }
    return dataArr;
}


class MovieInfo extends React.Component {
    constructor(props) {
        super(props);
        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });
        this.state = {
            movieId: this.props.location.search.split("=")[1] || 0,
            Movie: {},
            TypeList: [],
            ActorList: [],
            ImageList: [],
            dataSource,
            refreshing: true,
            isLoading: true,
            height: document.documentElement.clientHeight,
            useBodyScroll: false,
            vipId: cookies.load("vipId"),
            isLike: 0,
            imgHeight: 176
        }
    }

    componentDidMount() {
        if(this.state.vipId){
            http.get(`api/movie/vip/${this.state.movieId}/${this.state.vipId}`).then(({data}) => {
                console.log(data)
                if (data.code === 200) {
                    this.setState({
                        isLike: data.data.like
                    })
                } else {
                    Modal.alert("提示",data.msg);
                }
            })
        }else{
            this.setState({
                isLike:0
            })
        }

        http.get(`api/movie/info/${this.state.movieId}`, {page: this.props.pageInfo}).then(({data}) => {
            console.log(data)
            if (data.code === 200) {
                const Movie = data.data.movie;
                const TypeList = data.data.typeList;
                const ActorList = data.data.actorList;
                const ImageList = data.data.imageList;
                this.setState({
                    Movie,
                    TypeList,
                    ActorList,
                    ImageList
                }, () => {
                    console.log(this.state.TypeList)
                })
            } else {
                Modal.alert("提示",data.msg);
            }
        })
        const hei = this.state.height - 100;
        setTimeout(() => {
            this.rData = genData();
            this.setState({
                dataSource: this.state.dataSource.cloneWithRows(genData()),
                height: hei,
                refreshing: false,
                isLoading: false,
            });
        }, 10);
    }

    //刷新函数
    onRefresh = () => {
        this.setState({refreshing: true, isLoading: true});
        // 模拟初始Ajax
        setTimeout(() => {
            this.rData = genData();
            this.setState({
                //想要更新datasource中的数据，必须每次通过cloneWithRows这个来重新挂载datasource的值。
                dataSource: this.state.dataSource.cloneWithRows(this.rData),
                refreshing: false,
                isLoading: false,
            });
        }, 10);
    };
    //下拉回调函数
    onEndReached = (event) => {
        if (this.state.isLoading) {
            return;
        }
        this.setState({isLoading: true});
        setTimeout(() => {
            this.rData = [...this.rData, ...genData(++pageIndex)];
            this.setState({
                dataSource: this.state.dataSource.cloneWithRows(this.rData),
                isLoading: false,
            });
        }, 300);
    };
    // 取消收藏函数
    isCollect = () => {
        if(this.state.vipId){
            const collectInfo={
                "resourceId": this.state.movieId,
                "relationId": this.state.vipId,
                "relationType": 4,
                "collect": this.state.isLike?2:1
            }
            http.post(`api/collect`, collectInfo).then(({data}) => {
                console.log(data)
                if (data.code === 200) {
                    this.setState({
                        isLike:!this.state.isLike
                    })

                } else {
                    Modal.alert("提示",data.msg);
                }
            })
        }else{
            Modal.alert("提示","请先登录！",[{
                text:"确定",
                onPress:()=>{
                    this.props.history.push({pathname:"/login"})
                }
            }])
        }

    };

    renderMovieInfo() {
        const pageInfo={
            page:pageIndex+1,
            movieId: this.state.movieId
        }
        const row1 = () => {
            return (
                <ReviewList  movieapi={`api/movie/comment/list/${this.state.movieId}`}  pageInfo={pageInfo} history={this.props.history}   />
            )
        }
        const types = this.state.TypeList.map(item => {
            return <span key={item.typeId}  >{item.typeName}</span>
        })

        return (
            <div className={"MovieInfo-main"}>
                <WingBlank>
                    <Card>
                        <Card.Body>
                            <div className={"the-left"}>
                                <img
                                    src={process.env.REACT_APP_BASE_API + "/img/" + this.state.Movie.cover}
                                    style={{width: '100%'}}
                                />
                            </div>
                            <div className={"right"}>
                                <p className={"name"}>{this.state.Movie.name}</p>
                                <p className={"translationName"}>{this.state.Movie.translationName}</p>
                                <p className={"introduction"}>{this.state.introduction}</p>
                                <p className={"releaseDate"}>{this.state.Movie.releaseDate}</p>
                            </div>

                            <Button icon="check-circle-o" onClick={this.isCollect} inline size="small" style={{margin: '10px'}}>{this.state.isLike?"取消收藏":"收藏"}</Button>

                        </Card.Body>

                    </Card>
                    <WhiteSpace size="lg"/>
                    <div className={"introductionInfo"}>
                        {
                            types
                        }
                        <div className={"title"}>简介</div>
                        <div className={"text"}>
                            {this.state.Movie.introduction}
                        </div>
                        <div className={"title"}>演职人员</div>
                            <WingBlank>
                                <Carousel className={"space-carousel"}
                                          frameOverflow="visible"
                                          cellSpacing={10}
                                          slideWidth={0.8}
                                          infinite
                                          afterChange={index => this.setState({ slideIndex: index })}
                                >
                                    {
                                        this.state.ActorList.map(((item, index) => {
                                            return <Link to={`/actorInfo?actorId=${item.actorId}`}
                                                         key={index}
                                                         style={{
                                                display: 'block',
                                                position: 'relative',
                                                top: this.state.slideIndex === index ? -10 : 0,
                                                height: "180px"
                                            }}>
                                                <div style={{height:"100%"}}>
                                                    <p style={{textAlign:"center",height:"20px"}}>
                                                        {item.actorName}{this.state.Movie.director===item.actorId?'（导演）':''}
                                                    </p>
                                                    <img
                                                        src={process.env.REACT_APP_BASE_API + "/img/" + item.cover}
                                                        alt=""
                                                        style={{ width: '100%',height:"160px", verticalAlign: 'top' }}
                                                        onLoad={() => {
                                                            window.dispatchEvent(new Event('resize'));
                                                            this.setState({ imgHeight: 'auto' });
                                                        }}
                                                    />
                                                </div>

                                            </Link>
                                        }))
                                    }
                                </Carousel>
                            </WingBlank>
                        <div className={"title"}>剧照</div>
                        <div className={"imagesList"}>
                            {
                                <WingBlank>
                                    <Carousel className={"space-carousel"}
                                              frameOverflow="visible"
                                              cellSpacing={10}
                                              slideWidth={0.5}
                                              infinite
                                              afterChange={index => this.setState({ slideIndex: index })}
                                    >
                                        {
                                            this.state.ImageList.map(((item, index) => {
                                                return <a key={index} style={{
                                                    display: 'block',
                                                    position: 'relative',
                                                    height: "180px"
                                                }}>
                                                        <img
                                                            src={process.env.REACT_APP_BASE_API + "/img/" + item.imageSrc}
                                                            alt=""
                                                            style={{ width: '100%',height:"160px", verticalAlign: 'top' }}
                                                            onLoad={() => {
                                                                window.dispatchEvent(new Event('resize'));
                                                                this.setState({ imgHeight: 'auto' });
                                                            }}
                                                        />
                                                </a>
                                            }))
                                        }
                                    </Carousel>
                                </WingBlank>
                                })
                            }
                        </div>
                        <div className={"title"}>评论区
                            <Button icon="check-circle-o" onClick={() => this.props.history.push
                            ({ pathname: "/publishMovieReview", state: {movieId:this.state.movieId,vipId:this.state.vipId,movieName: this.state.Movie.name} })} inline size="small">添加评论</Button>
                        </div>
                    </div>
                    <div>
                        <div className={"reviewList"}>
                            <ListView
                                key={1}
                                ref={el => this.lv = el}
                                dataSource={this.state.dataSource}
                                renderFooter={() => (<div style={{padding: 30, textAlign: 'center'}}>
                                    {this.state.isLoading ? '加载中...' : '加载完成'}
                                </div>)}
                                renderRow={row1}
                                style={{
                                    height: this.state.height,
                                    margin: '0 0 0 20px',
                                }}
                                pullToRefresh={<PullToRefresh
                                    refreshing={this.state.refreshing}
                                    indicator={this.state.down ? {} : {deactivate: '下拉可以刷新'}}
                                    onRefresh={this.onRefresh}
                                />}
                                onEndReached={this.onEndReached}
                                onEndReachedThreshold={10}
                                pageSize={1}
                            />
                        </div>
                    </div>
                </WingBlank>


            </div>
        )

    }

    render() {
        return this.state.TypeList.length ? (
            <div className={"MovieInfo"}>
                <div className={"header"}>
                    <div onClick={() => this.props.history.goBack()}><DoubleLeftOutlined/>返回</div>

                </div>
                {
                    this.renderMovieInfo()
                }

            </div>


        ) : <></>;
    }
}

export default MovieInfo
